<template>
  <a-modal
    :maskClosable="false"
    :title="title"
    :width="1000"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭"
    destroyOnClose
  >
    <a-spin :spinning="confirmLoading">
      <a-form-model
        ref="newsForm"
        :model="form"
        :rules="rules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <a-form-model-item label="宠物名称" prop="name">
          <a-input placeholder="请输入宠物名称" v-model="form.name" />
        </a-form-model-item>

        <a-form-model-item label="封面" prop="cover">
          <a-upload
            action="http://localhost:4000/api/upload"
            list-type="picture-card"
            :file-list="fileList"
            @preview="handlePreview"
            @change="handleChange"
            :beforeUpload="beforeUpload"
          >
            <div v-if="fileList.length < 1">
              <a-icon type="plus" />
              <div class="ant-upload-text">Upload</div>
            </div>
          </a-upload>
          <a-modal
            :visible="previewVisible"
            :footer="null"
            @cancel="handlePreViewCancel"
          >
            <img alt="example" style="width: 100%" :src="previewImage" />
          </a-modal>
        </a-form-model-item>
        <a-form-model-item label="内容" prop="content">
          <a-textarea
            placeholder="请输入内容"
            v-model="form.content"
            :rows="4"
          />
        </a-form-model-item>

        <a-form-model-item label="启用状态">
          <a-switch
            checked-children="开"
            un-checked-children="关"
            v-model="form.status"
          />
        </a-form-model-item>
      </a-form-model>
    </a-spin>
  </a-modal>
</template>

<script>
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
}
import { postAction, getAction } from "@/api/basic";
import { formatFile, initFile } from "@/utils/util";
export default {
  name: "DogModal",
  components: {},
  data() {
    return {
      title: "操作",
      visible: false,
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      labelCol2: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      wrapperCol2: {
        xs: { span: 24 },
        sm: { span: 16 },
      },

      confirmLoading: false,
      form: {
        name: "",
        cover: "",
        content: "",
        status: false,
      },
      rules: {
        name: [{ required: true, message: "请输入宠物名称" }],
      },
      url: {
        add: "/dog/add",
        edit: "/dog/edit",
        queryById: "/dog/queryById",
      },
      previewVisible: false,
      previewImage: "",
      fileList: [],
    };
  },
  created() {},
  methods: {
    add() {
      this.edit({});
    },
    edit(record) {
      this.model = Object.assign({}, record);
      if (record.id) {
        getAction(this.url.queryById, { id: record.id })
          .then((res) => {
            if (res.success) {
              this.form = Object.assign({}, res.result);
              this.form.status = this.form.status == 1 ? true : false;
              this.fileList = this.form.cover
                ? initFile(JSON.parse(this.form.cover))
                : [];
            }
          })
          .finally(() => {
            this.visible = true;
          })
          .catch(() => {
            this.$message.error("服务器出错了，请稍后重试");
          });
      } else {
        this.visible = true;
      }
    },
    close() {
      this.$emit("close");
      this.confirmLoading = false;
      this.form = {
        name: "",
        cover: "",
        content: "",
        status: false,
      };
      this.visible = false;
      this.fileList = [];
      this.previewImage = "";
    },
    handleOk() {
      const that = this;
      // 触发表单验证
      this.$refs.newsForm.validate((valid) => {
        if (valid) {
          // if (this.fileList.length < 1) {
          //   this.$message.warning("请选择一张封面图");
          //   return;
          // }
          that.confirmLoading = true;
          let httpurl = "";

          if (!this.model.id) {
            httpurl += this.url.add;
          } else {
            httpurl += this.url.edit;
          }
          let formData = Object.assign({}, this.form);
          //时间格式化

          formData.cover = JSON.stringify(formatFile(this.fileList));
          formData.status = formData.status ? 1 : 0;
          console.log(formData);
          postAction(httpurl, formData)
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message);
                that.confirmLoading = false;
                that.$emit("ok");
                that.close();
              } else {
                that.$message.warning(res.message);
                that.confirmLoading = false;
              }
            })
            .finally(() => {
              that.confirmLoading = false;
            })
            .catch((res) => {
              this.$message.error("服务器出错了，请稍后重试");
            });
        } else {
          that.confirmLoading = false;
          return false;
        }
      });
    },
    handleCancel() {
      this.close();
    },
    handlePreViewCancel() {
      this.previewVisible = false;
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
      }
      this.previewImage = file.url || file.preview;
      this.previewVisible = true;
    },
    handleChange({ fileList }) {
      this.fileList = fileList;
    },
    beforeUpload(file) {
      const isJpgOrPng =
        file.type === "image/jpeg" || file.type === "image/png";
      if (!isJpgOrPng) {
        this.$message.error("只能上传jpeg和png图片!");
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("图片只能小于2M!");
      }
      return isJpgOrPng && isLt2M;
    },
  },
};
</script>

<style lang="less" scoped>
</style>
